package timo.rabbitmq.test.study.route;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import lombok.SneakyThrows;
import timo.rabbitmq.common.CommonUtils;

import java.util.Random;
import java.util.Scanner;

/**
 * 路由模式 --
 * 只订阅所有消息中的一部分
 * 继承于 PubSubTest 更换交换机 添加路由
 * @author timo
 * @date 2022/7/6
 */
public class RouteTestMain {

    //producer
    //这里模拟耗时任务,发送的消息中,每个点使工作进程暂停一秒钟,例如"Hello..."将花费3秒钟来处理
    @SneakyThrows
    public static void main(String[] args) {
        Connection connection = CommonUtils.getConnection();
        Channel channel = connection.createChannel();

        String[] a = {"warning", "info", "error"};
//        String[] a = {"info", "error"};

        //直连交换机
        //参数1: 交换机名
        //参数2: 交换机类型
        channel.exchangeDeclare("direct_logs", BuiltinExchangeType.DIRECT);

        while (true) {
            //控制台输入的消息发送到rabbitmq
            System.out.print("输入消息: ");
            String msg = new Scanner(System.in).nextLine();
            //如果输入的是"exit"则结束生产者进程
            if ("exit".equals(msg)) {
                break;
            }
            //随机产生日志级别
            String level = a[new Random().nextInt(a.length)];

            //参数1: 交换机名
            //参数2: routingKey, 路由键,这里我们用日志级别,如"error","info","warning"
            //参数3: 其他配置属性
            //参数4: 发布的消息数据
            channel.basicPublish("direct_logs", level, null, msg.getBytes());
            System.out.println("消息已发送: "+level+" - "+msg);
        }
        connection.close();
        channel.close();
    }


}
